"use client";
import React, { useEffect, useState } from "react";
import { TreeSelect } from "antd";
import type { TreeSelectProps } from "antd";
import {
  Drawer,
  Tabs,
  Input,
  Select,
  Form,
  Button,
  Table,
  Space,
  Modal,
  Popconfirm,
  Tag,
} from "antd";
import {
  SearchOutlined,
  DeleteOutlined,
  HourglassOutlined,
  PlusOutlined,
  UnorderedListOutlined,
  RedoOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  VerticalAlignTopOutlined,
  EditOutlined,
  CheckCircleTwoTone,
} from "@ant-design/icons";
import type { TableColumnsType, TableProps } from "antd";
import Modals from "@/app/[locale]/hbs/modal";
import axios from "axios";
type TableRowSelection<T extends object = object> =
  TableProps<T>["rowSelection"];

interface DataType {
  id: number;
  name: string;
  khzt: string;
  khxj: number;
  lxr: string;
  phone: number;
  time: number;
  timefalse: number;
}
export default function Lsy() {
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    console.log("selectedRowKeys changed: ", newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection: TableRowSelection<DataType> = {
    selectedRowKeys,
    onChange: onSelectChange,
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE,
      {
        id: "odd",
        text: "Select Odd Row",
        onSelect: (changeableRowKeys) => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changeableRowKeys.filter((_, index) => {
            if (index % 2 !== 0) {
              return false;
            }
            return true;
          });
          setSelectedRowKeys(newSelectedRowKeys);
        },
      },
      {
        key: "even",
        text: "Select Even Row",
        onSelect: (changeableRowKeys) => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changeableRowKeys.filter((_, index) => {
            if (index % 2 !== 0) {
              return true;
            }
            return false;
          });
          setSelectedRowKeys(newSelectedRowKeys);
        },
      },
    ],
  };

  const columns: TableColumnsType<DataType> = [
    {
      title: "订单编号",
      dataIndex: "time",
      width: 150,
      sorter: {
        compare: (a, b) => a.time - b.time,
        multiple: 2,
      },
      showSorterTooltip:false,
    },
    {
      title: "订单标题",
      dataIndex: "khzt",
      width: 130,
      render: (khzt, record) => <a>{khzt}</a>,
    },
    {
      title: "关联客户",
      dataIndex: "name",
      width: 220,
      render: (name, record) => <a>{name}</a>,
    },
    {
      title: "审批状态",
      dataIndex: "start",
      width: 100,
      render: (name, record) => (
        <span>
          {name ? (
            <Tag icon={<CheckCircleOutlined />} color="success">
              已通过
            </Tag>
          ) : (
            <Tag icon={<CloseCircleOutlined />} color="error">
              未提交
            </Tag>
          )}
        </span>
      ),
    },
    {
      title: "订单总金额",
      dataIndex: "phone",
      width: 130,
      sorter: {
        compare: (a, b) => a.phone - b.phone,
        multiple: 1,
      },
      showSorterTooltip:false,
    },
    ,
    {
      title: "已回款金额",
      dataIndex: "phone",
      width: 130,
      sorter: {
        compare: (a, b) => a.phone - b.phone,
        multiple: 1,
      },
      showSorterTooltip:false,
    },
    {
      title: "已开票金额",
      dataIndex: "phone",
      width: 130,
      sorter: {
        compare: (a, b) => a.phone - b.phone,
        multiple: 1,
      },
      showSorterTooltip:false,
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space style={{ fontSize: "12px" }}>
          <a>
            <CheckCircleTwoTone />
            更进
          </a>
          <a
            onClick={() => {
              setTitle("编辑");
              showModal();
              setObjItem({record});
            }}
          >
            <EditOutlined />
            编辑
          </a>
          <a
            onClick={() => {
              let index = data.findIndex((item) => item.id == record.id);
              console.log(index, "/置顶的下标");
              data.splice(index, 1); // data.unshift(record);
              console.log(data, "/置顶后的数组");
              setDate([record, ...data]);
            }}
          >
            <VerticalAlignTopOutlined />
            置顶
          </a>
          <Popconfirm
            title="删除提示"
            description="是否确定删除?"
            onConfirm={async () => {
              await axios.delete(`http://localhost:3000/data/${record.id}`, {
                headers: { "Content-Type": "application/json" },
              });
              getDate();
            }}
            okText="Yes"
            cancelText="No"
          >
            <a>
              <DeleteOutlined />
              删除
            </a>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const [data, setDate] = useState([]);
  let [form] = Form.useForm();
  // 获取所有数据
  const getDate = async () => {
    let res = await axios
      .get("http://localhost:3000/data")
      .then((res) => res.data);
    setDate(res);
  };

  useEffect(() => {
    getDate();
  }, []);

  const [isModalOpen, setIsModalOpen] = useState(false);

  const [title, setTitle] = useState("添加");
  const [objItem, setObjItem] = useState({});

  const showModal = () => {
    setIsModalOpen(true);
  };

  // 编辑数据
  const handleOk = async (obj: any) => {
    setIsModalOpen(false);
    await axios.patch(`http://localhost:3000/data/${obj.id}`, obj, {
      headers: { "Content-Type": "application/json" },
    });
    getDate();
  };

  // 添加数据
  const handleCancel = async (obj: any) => {
    setIsModalOpen(false);
    await axios.post("http://localhost:3000/data", {time:+new Date(),...obj}, {
      headers: { "Content-Type": "application/json" },
    });
    getDate();
  };

  const [keyword, setKeyword] = useState("");
  const [customerStatus, setCustomerStatus] = useState("");
  const [customerType, setCustomerType] = useState("");
  const [lastFollowUp, setLastFollowUp] = useState("");

  // 搜索事件
  const handleSearch = async () => {
    try {
      const response = await axios.get("http://localhost:3000/data", {
        params: {
          khzt_like: keyword != "" ? keyword : undefined,
          khxj: customerStatus != "" ? customerStatus : undefined,
          name: customerType != "" ? customerType : undefined,
          time: lastFollowUp != "" ? lastFollowUp : undefined,
        },
      });
      setDate(response.data);
      console.log(keyword);

      // getDate()
    } catch (error) {
      console.error("搜索出错:", error);
    }
  };
  //树形下拉
  //下拉输入框
  const [value, setValue] = useState<string>();

  const onChange = (newValue: string) => {
    // setValue(newValue);
    setCustomerType(newValue);
  };

  const onPopupScroll: TreeSelectProps["onPopupScroll"] = (e) => {
    console.log("onPopupScroll", e);
  };
  const [treeData, settreeData] = useState([
    {
      value: "广州市新创智能科技有限公司",
      label: "广州市新创智能科技有限公司",
    },
    {
      value: "东莞市华科电子有限公司",
      label: "东莞市华科电子有限公司",
    },
    {
      value: "佛山市星辰软件科技有限公司",
      label: "佛山市星辰软件科技有限公司",
    },
    {
      value: "惠州市旭日科技有限公司",
      label: "惠州市旭日科技有限公司",
    },
    {
      value: "珠海市海韵信息技术有限公司",
      label: "珠海市海韵信息技术有限公司",
    },
    {
      value: "中山市宏业科技发展有限公司",
      label: "中山市宏业科技发展有限公司",
    },
    {
      value: "江门市创想科技有限公司",
      label: "江门市创想科技有限公司",
    },
    {
      value: "汕头市华宇科技有限公司",
      label: "汕头市华宇科技有限公司",
    },
    {
      value: "湛江市鑫达科技有限公司",
      label: "湛江市鑫达科技有限公司",
    },
    {
      value: "肇庆市联创科技有限公司",
      label: "肇庆市联创科技有限公司",
    },
  ]);
   //抽屉
    const [open, setOpen] = useState(false);
    const showDrawer = () => {
      setOpen(true);
    };
    const onClose = () => {
      setOpen(false);
    };
  return (
    <div
      style={{
        margin: "0 auto",
        backgroundImage: "none",
        textAlign: "left",
        height: "700px",
        overflow: "auto",
      }}
    >
      {/* 头部tab标签 */}
      <div>
        <Tabs
          defaultActiveKey="1"
          items={[
            {
              label: "全部订单",
              key: "1",
              // children: '全部客户',
            },
            {
              label: "我的订单",
              key: "2",
              // children: '我的客户',
            },
            {
              label: "下属订单",
              key: "3",
              // children: '下属客户',
            },
            {
              label: "我协作的",
              key: "5",
              // children: '我协作的',
            },
            {
              label: "下属协作",
              key: "6",
              // children: '下属协作的',
            },
          ]}
        />
      </div>
      {/* 搜索栏 */}
      <div style={{ display: "flex", backgroundColor: "white" }}>
        <Form style={{ display: "flex", backgroundColor: "white" }} form={form}>
          <Form.Item name="khzt" style={{ width: "190px", margin: "0 20px" }}>
            <Input
              placeholder="搜索关键字"
              value={keyword}
              onChange={(e) => setKeyword(e.target.value)}
            />
          </Form.Item>
          <Form.Item name="khxj" style={{ width: "190px", margin: "0 20px" }}>
            <Select
              onChange={(e) => setCustomerStatus(e)}
              placeholder="商机阶段"
              options={[
                { value: "深入沟通", label: "深入沟通" },
                { value: "方案审核", label: "方案审核" },
                { value: "条款协商", label: "条款协商" },
                { value: "方案初定", label: "方案初定" },
                { value: "价格谈判", label: "价格谈判" },
                { value: "合作规划", label: "合作规划" },
                { value: "结果评估", label: "结果评估" },
                { value: "协议履行", label: "协议履行" },
                { value: "执行推进", label: "执行推进" },
                { value: "客户维护", label: "客户维护" },
              ]}
            />
          </Form.Item>
          <Form.Item name="name" style={{ width: "250px", margin: "0 20px" }}>
            <TreeSelect
              showSearch
              style={{ width: "250px" }}
              value={value}
              dropdownStyle={{ maxHeight: 400, overflow: "auto" }}
              placeholder="商机来源"
              allowClear
              treeDefaultExpandAll
              onChange={onChange}
              treeData={treeData}
              onPopupScroll={onPopupScroll}
            />
            .
          </Form.Item>
          <Button
            type="primary"
            icon={<SearchOutlined />}
            onClick={handleSearch}
          >
            查询
          </Button>
          <Button
            style={{ margin: "0 20px" }}
            icon={<RedoOutlined />}
            onClick={() => {
              form.resetFields();
              getDate();
            }}
          >
            重置
          </Button>
          <Button icon={<HourglassOutlined />} color="primary" variant="link" onClick={showDrawer}>
            报价金额
          </Button>
        </Form>
      </div>

      {/* 按钮 */}
      <div style={{ padding: "0 0 20px 20px" }}>
        <Button
          type="primary"
          icon={<PlusOutlined />}
          style={{ marginRight: "10px" }}
          onClick={() => {
            setTitle("添加");
            showModal();
            setObjItem({});
          }}
        >
          添加
        </Button>
      </div>
      {/* 表格列表 */}
      <div>
        <Table<DataType>
          rowSelection={rowSelection}
          columns={columns}
          dataSource={data}
          onChange={onChange}
          pagination={{ defaultCurrent: 1, defaultPageSize: 6 }}
          showSorterTooltip={{ target: "sorter-icon" }}
            rowKey='id'
        />
      </div>

      <Modal
        title={title}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
        footer={null}
      >
        <Modals
          title={title}
          onCancel={handleCancel}
          onOk={handleOk}
          objItem={objItem}
          key={new Date().getTime()}
        />
      </Modal>
        {/* 抽屉 */}
        <>
            <Drawer title="查看报价数据" onClose={onClose} open={open}>
              <div
                style={{
                  marginLeft: "10px",
                  background: "rgba(255, 255, 255)",
                }}
              ><div style={{display:'flex',justifyContent:'space-evenly',margin:'10px 0'}}>
                <h3>关联客户</h3>
                <h3>订单金额</h3>
              </div>
                {data.map((item) => {
                  return (
                    <div
                      style={{
                        display: "flex",
                        justifyContent: "space-between",
                        padding: "10px",
                        border:'1px solid '
                      }}
                    >
                      <span>{item.name}</span>
                      <span>{item.phone}</span>
                    </div>
                  );
                })}
              </div>
            </Drawer>
          </>
    </div>
  );
}
